package com.yunlin.protocal;
/*
    ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ 
       Author   :  lixiaodaoaaa
       Date     :  2018/6/4
       Time     :  20:15
    ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
 */


import com.yunlin.bean.BleDevice;
import com.yunlin.utils.BteKeyUtils;
import com.yunlin.utils.FormatUtils;
import com.yunlin.utils.SecureUtils;

public class BteProtocalCommandUtils{
    
    
    private static final String TAG="BteProtocalCommandUtils";
    
    
    private static String header=BTDataDefine.OPENLOCK_HEADER;
    private static String end=BTDataDefine.COMMON_DATA_END;
    
    public static String getHandShakeCommnd(BleDevice bleDevice){
        
        String funcionData=BteFunctionData.HAND_SHAKE;
        //01
        String macAddressCommand=BteProtocalUtils.reverseMacAddress(bleDevice.getMacAddress());
        // 反转
        String timeCommand=BteProtocalUtils.getHandShakeTimeCommand();
        //时间反转
        String needEncrpyCommand=BteProtocalUtils.getNeedEncodeCommand(funcionData + macAddressCommand + timeCommand);
        String encodeCommandAndXorCheck=getEncodeCommandAndXor(bleDevice, needEncrpyCommand);
        String lastCommand=BTDataDefine.COMMON_DATA_HEADER + encodeCommandAndXorCheck + BTDataDefine.COMMON_DATA_END;
        return lastCommand;
    }
    
    
    /**
     * 获取密文 以及  校验
     *
     * @return
     */
    public static String getEncodeCommandAndXor(BleDevice bleDevice, String needEncrpyCommand){
        byte[] key0Bytes=BteKeyUtils.getKey0Bytes(bleDevice.getMacAddress(), bleDevice.getK0());
        byte[] key1Bytes=BteKeyUtils.getKey1Bytes(bleDevice.getMacAddress(), bleDevice.getK1());
        
        //s0 = encodeResultBytes;
        byte[] s0EncodeBytes=null;
        byte[] s1EncodeBytes=null;
        try {
            s0EncodeBytes=SecureUtils.encrypt(key1Bytes, FormatUtils.strToBytes(needEncrpyCommand));
            s1EncodeBytes=SecureUtils.encrypt(key0Bytes, s0EncodeBytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte checkXorResult=BteProtocalUtils.getXor(s1EncodeBytes);
        String encodeCommand=FormatUtils.bytesToHexString(s1EncodeBytes);
        String xorHexResult=FormatUtils.byteToHexStr(checkXorResult);
        return encodeCommand + xorHexResult;
    }
    
    
    private static String getSecureDataByReadData(String readData){
        if ("aa".equals(readData.substring(0, 2).toLowerCase())) {
            readData=readData.substring(2, readData.length());
        }
        
        if ("55".equals(readData.substring(readData.length() - 2, readData.length()))) {
            readData=readData.substring(0, readData.length() - 2);
        }
        return readData;
    }
    
    
    /**
     * 通信加密说明
     * (1)密钥池
     * 蓝牙mac的累加和，取低字节(只取1个字节)，记为temp
     * 蓝牙mac最低字节为单数，则密钥池所有字节加上temp
     * 蓝牙mac最低字节为双数，则密钥池所有字节与temp异或
     * (1)密钥编号
     * 蓝牙广播内容为K0K1
     * K0K1为密钥编号，解密时先用K0对应的密钥解密再用K1对应的密钥解密，反之加密时先K1再K0
     *
     * @param reiveData
     * @return
     */
    
    public static String decodeReiceveData(BleDevice bleDevice, String reiveData){
        byte[] key0Bytes=BteKeyUtils.getKey0Bytes(bleDevice.getMacAddress(), bleDevice.getK0());
        byte[] key1Bytes=BteKeyUtils.getKey0Bytes(bleDevice.getMacAddress(), bleDevice.getK1());
        
        String securetDataStr=getSecureDataByReadData(reiveData);
        String dataEnd=securetDataStr.substring(securetDataStr.length() - 2, securetDataStr.length());
        
        //开锁指令的回复
        //BB4F4B
        if (dataEnd.contains("66") && securetDataStr.length() != 32) {
            return securetDataStr;
        }
        
        if (securetDataStr.length() >= 32) {
            securetDataStr=securetDataStr.substring(0, 32);
        }
        
        byte[] s0=null;
        byte[] s1=null;
        
        try {
            s0=SecureUtils.decrypt(key0Bytes, FormatUtils.strCommandToBytes(securetDataStr));
            s1=SecureUtils.decrypt(key1Bytes, s0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        if (s1 != null) {
            return FormatUtils.bytesToHexString(s1);
            
        }else {
            return "";
        }
    }
    
    /**
     * 得到用户信息
     */
    public static String getDeviceInfo(BleDevice bleDevice){
        String header=BTDataDefine.COMMON_DATA_HEADER;
        String end=BTDataDefine.COMMON_DATA_END;
        String functionData=BteFunctionData.READ_DEVICE_INFO;
        String needEncodeCommand=BteProtocalUtils.getNeedEncodeCommand(functionData);
        String encodeCommandAndXor=getEncodeCommandAndXor(bleDevice, needEncodeCommand);
        return header + encodeCommandAndXor + end;
    }
    
    
    /**
     * 得到管理员认证命令行
     *
     * @return
     */
    public static String getAdminVerify(BleDevice bleDevice, String pwd){
        String header=BTDataDefine.COMMON_DATA_HEADER;
        String end=BTDataDefine.COMMON_DATA_END;
        String openLockPwdCommand=BteProtocalUtils.getOpenLockPwdCommand(pwd);
        String functionData=BteFunctionData.VERIFY + openLockPwdCommand;
        
        String needEncodeCommand=BteProtocalUtils.getNeedEncodeCommand(functionData);
        String encodeCommandAndXor=getEncodeCommandAndXor(bleDevice, needEncodeCommand);
        return header + encodeCommandAndXor + end;
    }
    
    /**
     * AA023132333435360000000000000000000555
     * (开锁授权码为"123456的例子")
     *
     * @return
     */
    public static String getOpenLockCommand(BleDevice bleDevice, String pwd){
        String header=BTDataDefine.COMMON_DATA_HEADER;
        String end=BTDataDefine.COMMON_DATA_END;
        String openLockPwdCommand=BteProtocalUtils.getOpenLockPwdCommand(pwd);
        String functionData=BteFunctionData.OPEN_LOCK + openLockPwdCommand;
        String needEncodeCommand=BteProtocalUtils.getNeedEncodeCommand(functionData);
        String encodeCommandAndXor=getEncodeCommandAndXor(bleDevice, needEncodeCommand);
        return header + encodeCommandAndXor + end;
    }
    
}
